package com.bjsxt.userscenter.common.util;

import javax.annotation.Resource;
import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;

import org.springframework.mail.MailException;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;

/**
 * spring发送的邮件的工具类
 * @author zxj
 *
 */
@Component("springEmialUtil")
public class SpringEmailUtil
{
	@Resource(name="javaMailSenderImpl")
    private JavaMailSender javaMailSender;
	@Resource
    private SimpleMailMessage simpleMailMessage;
	/**
	 * 发送邮件
	 */
	public boolean sendMail(String to,String subject,String text)
	{
		try
		{
			this.simpleMailMessage.setTo(to);
			this.simpleMailMessage.setSubject(subject);
			this.simpleMailMessage.setText(text);
			this.javaMailSender.send(simpleMailMessage);
		} catch (MailException e)
		{
			ConstatFinalUtil.LOGGER.error("-发送邮件失败了--to:{},subject:{},text:{}-",to,subject,text,e);
		}
		return false;
	}
	/**
	 * 发送邮件，解析Html
	 */
	public boolean sendMailHtml(String to,String subject,String text)
	{
		try
		{
			MimeMessage message=this.javaMailSender.createMimeMessage();
			/*true:表示发送的邮件是附文件，并设置编码*/
			MimeMessageHelper helper=new MimeMessageHelper(message,true,"UTF-8");
			/*设置邮件的相关信息*/
			helper.setFrom(this.simpleMailMessage.getFrom());
			helper.setTo(to);
			helper.setSubject(subject);
			/*表示富文件*/
			helper.setText(text,true);
			this.javaMailSender.send(message);
			ConstatFinalUtil.LOGGER.info("---- 发送邮件HTML成功了 ---to:{},subject:{},text:{}-",
					to,subject,text);
			return true ; 
		} catch (Exception e)
		{
			ConstatFinalUtil.LOGGER.error("-发送邮件失败了--to:{},subject:{},text:{}-",to,subject,text,e);
		} 
          return false;
	}
}
